package ru.urfc.portal.ui.client.googlets.client;

import ru.urfc.portal.ui.client.BaseGooglet;
import ru.urfc.portal.ui.client.controllers.GridController;
import ru.urfc.portal.ui.client.controllers.events.GetEvent;
import ru.urfc.portal.ui.client.descriptor.GridDescriptor;
import ru.urfc.portal.ui.client.descriptor.GridField;
import ru.urfc.portal.ui.client.model.catalogs.DeviceState;
import ru.urfc.portal.ui.client.widgets.DeviceFilter;
import ru.urfc.portal.ui.client.widgets.MegaGrid;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Widget;

public class DeviceList extends BaseGooglet {

	interface Binder extends UiBinder<Widget, DeviceList> {}
	private static Binder binder = GWT.create(Binder.class);

	@UiField Element title;
	@UiField DeviceFilter deviceFilter;
	@UiField MegaGrid grid;
	@UiField Button search;
	
	public Type<GridController> SEARCH = new Type<GridController>();

	@UiHandler("search")
	void search(ClickEvent e) {
		getEventsDispatcher().fireEvent(new GetEvent(SEARCH));
	}
	
	@Override
	protected void init() {
		initWidget(binder.createAndBindUi(this));
		title.setInnerText("РЭС на балансе");
		deviceFilter.setupButton(search.getElement());
		deviceFilter.init(this);

		GridDescriptor descriptor = new GridDescriptor(DEVICE_WITH_NET, CLIENTS, getClientId(), DEVICES);
		GridField autoExpandColumnField = createColumns(descriptor);
		
		register(SEARCH, createController(descriptor, grid)).setFilter(deviceFilter);
		grid.setAutoExpandColumn(autoExpandColumnField.getName());
	}

	static public GridField createColumns(GridDescriptor descriptor) {
		descriptor.setAddFieldPathPrefix("device");
		GridField autoExpandColumnField = NetDeviceList.createColumns(descriptor);
		descriptor.addCompositeField("city", "address").assignColumn(", ", "Адрес", 200);
		descriptor.addCIColumn("state/text", "state/code", DeviceState.class, "Статус", 100);
		descriptor.setAddFieldPathPrefix("");
		descriptor.addAnchorColumn("net/name", "net/id", PAGE_NET_DETAILS, "Радиосеть", 100);
		return autoExpandColumnField;
	}

}